package cn.sdc.sfw.util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BeanUtil {
	
	/**
	 * copy Bean from fromBean to toBean.
	 * 
	 * @param fromBean
	 * @param toBean
	 */
	public static void copyBean(Object fromBean, Object toBean) {
		copyBean(fromBean, toBean);
	}

	/**
	 * copy Bean from fromBean to toBean except that field's name in fieldNames.
	 * 
	 * @param from
	 * @param to
	 * @param fieldNames : 
	 */
	public static void copyBean(Object fromBean, Object toBean,
			String... filteredFieldNames) {
		String[] temp = new String[filteredFieldNames.length + 1];
		System.arraycopy(filteredFieldNames, 0, temp, 0, filteredFieldNames.length);
		temp[filteredFieldNames.length] = "serialVersionUID";
		copyExpectedFiledBean(fromBean, toBean, temp, false);
	}
	
	/**
	 * copy Bean from fromBean to toBean include that field's name in fieldNames.
	 * @param fromBean
	 * @param toBean
	 * @param expectedFieldNames
	 */
	public static void copyExpectedFiledBean(Object fromBean, Object toBean,
			String... expectedFieldNames) {
		copyExpectedFiledBean(fromBean, toBean, expectedFieldNames, true);
	}
	
	private static void copyExpectedFiledBean(Object fromBean, Object toBean,
			String[] FieldNames, boolean isExpected){
		
		if (fromBean == null || toBean == null) {
			return;
		}
		Field[] toFields = toBean.getClass().getDeclaredFields();
		Object value;
		String fieldName;
		List<String> fieldNamesArr = new ArrayList<String>();
		if (FieldNames != null && FieldNames.length > 0) {
			fieldNamesArr = Arrays.asList(FieldNames);
		}
		for (int i = 0; i < toFields.length; i++) {
			fieldName = toFields[i].getName();
			if( isExpected && fieldNamesArr.contains(fieldName) ){
					value = ReflectUtil.getFieldValue(fromBean, fieldName);
					ReflectUtil.setFieldValue(toBean, fieldName, value);
			}
			if(! (isExpected || fieldNamesArr.contains(fieldName)) ){
					value = ReflectUtil.getFieldValue(fromBean, fieldName);
					ReflectUtil.setFieldValue(toBean, fieldName, value);
			}
		}
	}
	
	

}
